package com.zhenhunfan;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.util.concurrent.TimeUnit;

/**
 * <p>Title: 双向流式RPC</p>
 * <p>Description:</p>
 *
 * @author zhanghong
 * @date 2023/7/17
 */
public class HelloGrpcClient5 {
    public static void main(String[] args) {
        //1.创建通信的管道
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 9000)
                .usePlaintext().build();
        try {
            //2.获得代理对象 stub

            HelloServiceGrpc.HelloServiceStub helloServiceStub = HelloServiceGrpc.newStub(managedChannel);

            StreamObserver<HelloProto.HelloRequest> helloRequestStreamObserver = helloServiceStub.cs2ss(new StreamObserver<HelloProto.HelloResponse>() {
                /**
                 * 服务端响应了一个消息监听事件
                 * @param helloResponse 响应
                 */
                @Override
                public void onNext(HelloProto.HelloResponse helloResponse) {
                    System.out.println(helloResponse.getResult());
                }

                @Override
                public void onError(Throwable throwable) {

                }

                /**
                 * 全部传输完事件
                 */
                @Override
                public void onCompleted() {
                    System.out.println("服务器处理完了");
                }
            });

            for (int i = 0; i < 9; i++) {
                //-----3.1 创建响应对象的构建者-----
                HelloProto.HelloRequest.Builder builder = HelloProto.HelloRequest.newBuilder();
                //-----3.2 填充数据-----
                builder.setName("镇魂帆" + i);
                HelloProto.HelloRequest helloRequest = builder.build();
                helloRequestStreamObserver.onNext(helloRequest);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            helloRequestStreamObserver.onCompleted();
            managedChannel.awaitTermination(1,TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            managedChannel.shutdown();
        }
    }
}
